﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIBindTransPos : MonoBehaviour
{
    public Transform tran;
    RectTransform rectTransform;
    public Vector3 offset;
   public  Canvas m_canvas;
    private void Start()
    {
        rectTransform = GetComponent<RectTransform>();
    }

    private void Update()
    {
        if (tran!=null)
        {
            rectTransform.anchoredPosition = WorldPosToUIPos(tran.position+offset, m_canvas);
        }
    }
    public void Bind(Transform tr,Vector3 offset,Canvas canvas)
    {
        tran = tr;
        this.offset = offset;
        this.m_canvas = canvas;
        gameObject.SetActive(true);
    }
    public void OnDisable()
    {
        tran = null;
        offset = Vector3.zero;
    }


    public Vector2 WorldPosToUIPos(Vector3 worldPos, Canvas canvas)
    {
        var viewPos = Camera.main.WorldToViewportPoint(worldPos);
        if (viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1)
        {
            float sheight = viewPos.y * Screen.height;
            float swidth = viewPos.x * Screen.width;
            var cs = canvas.GetComponent<CanvasScaler>();
            float weight = swidth * cs.referenceResolution.x / Screen.width;
            float height = sheight * cs.referenceResolution.y / Screen.height;
            return new Vector2(weight, height);
        }
        return -Vector2.one;
    }
}
